package com.loser.gateway.netty.base;

import com.loser.gateway.base.Dispatcher;
import com.loser.gateway.consts.WebSocketConst;
import com.loser.gateway.netty.biz.WebSocketNettyServerConnectionIpFilterHandler;
import com.loser.gateway.netty.biz.WebSocketNettyServerHandler;
import com.loser.gateway.netty.biz.WebSocketNettyServerRealIpHandler;
import com.loser.gateway.netty.coder.ProtostuffDecoder;
import com.loser.gateway.netty.coder.ProtostuffEncoder;
import com.loser.gateway.netty.coder.WebSocketNettyServerMessageDecoder;
import com.loser.gateway.netty.coder.WebSocketNettyServerMessageEncoder;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketFrameAggregator;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.codec.http.websocketx.extensions.compression.WebSocketServerCompressionHandler;
import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender;
import io.netty.handler.ipfilter.RuleBasedIpFilter;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.handler.timeout.IdleStateHandler;

import java.util.concurrent.TimeUnit;

/**
 * @Desc 配置netty pipeline
 * @Author loser
 * @Date 2021/3/2 9:22
 **/
public class WebSocketNettyServerInitializer extends ChannelInitializer<SocketChannel> {

    private final Dispatcher dispatcher;

    public WebSocketNettyServerInitializer(Dispatcher dispatcher) {
        this.dispatcher = dispatcher;
    }

    @Override
    protected void initChannel(SocketChannel socketChannel) {

        ChannelPipeline pipeline = socketChannel.pipeline();
        pipeline.addLast(new RuleBasedIpFilter(new WebSocketNettyServerConnectionIpFilterHandler()));
        pipeline.addLast(new HttpServerCodec());
        pipeline.addLast(new ChunkedWriteHandler());
        pipeline.addLast(new HttpObjectAggregator(WebSocketConst.MAX_CONTENT_LENGTH));
        pipeline.addLast(new WebSocketNettyServerRealIpHandler());
        pipeline.addLast(new IdleStateHandler(WebSocketConst.READER_IDLE_TIME, WebSocketConst.WRITE_IDLE_TIME, WebSocketConst.ALL_IDLE_TIM, TimeUnit.SECONDS));
        pipeline.addLast(new WebSocketFrameAggregator(10 * 1024 * 1024));
        pipeline.addLast(new WebSocketServerProtocolHandler(WebSocketConst.WEB_SOCKET_PATH));
        pipeline.addLast(new WebSocketServerCompressionHandler());
        pipeline.addLast(new ProtobufVarint32LengthFieldPrepender());
        pipeline.addLast(new WebSocketNettyServerMessageDecoder());
        pipeline.addLast(new ProtostuffDecoder());
        pipeline.addLast(new WebSocketNettyServerMessageEncoder());
        pipeline.addLast(new ProtostuffEncoder());
        pipeline.addLast(new WebSocketNettyServerHandler(dispatcher));

    }

}
